package com.lyh.controller;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.lyh.pojo.Provider;
import com.lyh.pojo.User;
import com.lyh.service.bill.BillService;
import com.lyh.service.provider.ProviderService;
import com.lyh.utils.Constants;
import com.lyh.utils.PageSupport;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/provider")
public class ProviderController {

    public ProviderService providerService;

    @Autowired
    public void setProviderService(ProviderService providerService) {
        this.providerService = providerService;
    }

    @RequestMapping("/proList")
    @ResponseBody
    public List proList() throws JsonProcessingException {
        //ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);

        List<Provider> providerNameList = providerService.getProviderNameList();
/*        ObjectMapper objectMapper = new ObjectMapper();
        String s = objectMapper.writeValueAsString(providerNameList);*/
        return providerNameList;
    }

    @RequestMapping("/providerList")
    public String providerList(Model model,
                               @RequestParam(name = "queryProCode",required = false) String proCode,
                               @RequestParam(name = "queryProName",required = false) String proName,
                               @RequestParam(name = "pageIndex",required = false) String pageNo) {

        HashMap<String, Object> map = new HashMap<>();
        int currentPageNo = 1;

        if (StringUtils.isNullOrEmpty(proCode)) {
            map.put("proCode",null);
        } else {
            map.put("proCode",proCode.trim());
        }

        if (StringUtils.isNullOrEmpty(proName)) {
            map.put("proName",null);
        } else {
            map.put("proName",proName.trim());
        }

        if (StringUtils.isNullOrEmpty(pageNo)) {
            map.put("currentPageNo",currentPageNo);
        } else {
            currentPageNo = Integer.valueOf(pageNo.trim());
        }

        //ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);
        //就算查询总数量
        int proCount = providerService.getCount(map);

        // 计算页数
        PageSupport pageSupport = new PageSupport();
        // 设置每页显示数量
        pageSupport.setPageSize(6);
        // 设置需要显示得总数，并计算总页数
        pageSupport.setTotalCount(proCount);
        // 获取总页数
        int totalPageCount = pageSupport.getTotalPageCount();
        // 设置当前页面
        pageSupport.setCurrentPageNo(currentPageNo);

        //控制首页和尾页的正常值
        if(currentPageNo<1){
            currentPageNo=1;
        }else if(currentPageNo>totalPageCount){
            currentPageNo=totalPageCount;
        }

        // 计算需要显示的数据的开始下标
        map.put("currentPageNo",(currentPageNo-1)*6);
        // 设置从该下标起显示个数
        map.put("PageSize",6);

        List<Provider> providerList = providerService.getProviderList(map);

        model.addAttribute("providerList",providerList);

        model.addAttribute("queryProCode",proCode);
        model.addAttribute("queryProName",proName);
        model.addAttribute("totalPageCount",totalPageCount);
        model.addAttribute("totalCount",proCount);
        model.addAttribute("currentPageNo",currentPageNo);

        return "providerlist";
    }

    @RequestMapping("/viewProvider/{proId}")
    public String viewProvider(@PathVariable("proId") String proId, Model model) {

        //ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);

        Provider provider = providerService.getProviderById(Integer.valueOf(proId));
        model.addAttribute("provider",provider);

        return "providerview";
    }


    @RequestMapping("/toModifyProvider/{proId}")
    public String toModifyProvider(@PathVariable("proId") String proId, Model model) {

       // ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);

        Provider provider = providerService.getProviderById(Integer.valueOf(proId));
        model.addAttribute("provider",provider);

        return "providermodify";
    }

    @RequestMapping("/checkProCode")
    @ResponseBody
    public String checkProCode(@RequestParam(name = "proCode") String proCode) {
        //ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);

        HashMap<String, String> map = new HashMap<>();
        if (StringUtils.isNullOrEmpty(proCode)) {
            map.put("message","null");
        } else {
            int i = providerService.checkProCode(proCode);

            if (i > 0) {
                map.put("message","exist");
            } else {
                map.put("message","noExist");
            }
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String s = null;
        try {
            s = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;
    }

    @GetMapping ("/modifyProvider")
    @ResponseBody
    public void modifyProvider(HttpServletRequest request, HttpServletResponse response) {

        String proCode = request.getParameter("proCode");
        String proName = request.getParameter("proName");
        String proContact = request.getParameter("proContact");
        String proPhone = request.getParameter("proPhone");
        String proAddress = request.getParameter("proAddress");
        String proFax = request.getParameter("proFax");
        String proDesc = request.getParameter("proDesc");
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);

        Provider provider = new Provider(proCode,proName,proDesc,proContact, proPhone,proAddress,proFax);

        provider.setModifyBy(user.getId());
        provider.setModifyDate(new Date());

        //ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);
        int i = providerService.modifyProvider(provider);

        if (i > 0) {
            System.out.println("provider修改成功");
            try {
                request.getRequestDispatcher("providerList").forward(request,response);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        } else {
            System.out.println("provider修改失败");
            request.setAttribute("message","修改信息失败");
        }

    }

    @RequestMapping("/toAddProvider")
    public String toAddProvider() {
        return "provideradd";
    }

    @GetMapping("addProvider")
    @ResponseBody
    public void addProvider(HttpServletRequest request,HttpServletResponse response) {
        //ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);

        String proCode = request.getParameter("proCode");
        String proName = request.getParameter("proName");
        String proContact = request.getParameter("proContact");
        String proPhone = request.getParameter("proPhone");
        String proAddress = request.getParameter("proAddress");
        String proFax = request.getParameter("proFax");
        String proDesc = request.getParameter("proDesc");
        User user = (User) request.getSession().getAttribute(Constants.USER_SESSION);

        Provider provider = new Provider(proCode,proName,proDesc,proContact, proPhone,proAddress,proFax);

        provider.setCreatedBy(user.getId());
        provider.setCreationDate(new Date());

        int i = providerService.addProvider(provider);

        if (i > 0) {
            try {
                request.getRequestDispatcher("providerList").forward(request,response);
            } catch (ServletException | IOException e) {
                e.printStackTrace();
            }
        } else {
            request.setAttribute("message","用户添加失败");
        }
    }

    @GetMapping("/deleteProvider/{proId}")
    @ResponseBody
    public String deleteProvider(@PathVariable("proId") String proId) {

        //ProviderService providerService = Constants.context.getBean("providerService", ProviderService.class);
        BillService billService = Constants.context.getBean("billService", BillService.class);
        HashMap<String, String> map = new HashMap<>();

        int i = billService.countProviderBills(proId);

        if (i > 0) {
            // 该供应商还存在订单交易，不可以删除
            map.put("delResult",String.valueOf(i));
        } else {
            // 没有订单交易的，才可以删除
            int j = providerService.deleteProvider(Integer.valueOf(proId));
            if (j > 0) {
                // 删除成功
                map.put("delResult","true");
            } else if (j == 0) {
                // 找不到删除对象
                map.put("delResult","notExist");
            }else {
                // 删除失败
                map.put("delResult","false");
            }
        }
        ObjectMapper objectMapper = new ObjectMapper();
        String s = null;
        try {
                s = objectMapper.writeValueAsString(map);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return s;
    }



}
